package top.ivansong92.example.leetcode.learning.data.struct.array.extension;

import java.util.Arrays;

public class NewArrayV2<E> {
    private E[] data;
    private int size;

    public NewArrayV2() {
        this(16);
    }

    public NewArrayV2(int capacity) {
        data = (E[]) new Object[capacity];
        size = 0;
    }

    public int size() {
        return size;
    }

    public int capatity() {
        return data.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    //增
    public void addFirst(E value) {
        add(value, 0);
    }

    public void addLast(E value) {
        add(value, size);
    }

    public void add(E value) {
        addLast(value);
    }

    public void add(E value, int index) {
        if (index < 0 || index > data.length) {
            throw new RuntimeException("index is ill");
        }

        if (size == Integer.MAX_VALUE) {
            throw new RuntimeException("array is full");
        }

        if (size >= data.length) {
            data = Arrays.copyOf(data, Math.min(Integer.MAX_VALUE, Math.max(0, data.length << 1)));
        }

        for (int i = size; i > index; i --) {
            data[i] = data[i - 1];
        }

        data[index] = value;
        size ++;
    }
    //删
    public void delete() {
        remove(1);
    }

    public E removeFirst() {
        return remove(0);
    }
    public E removeLast() {
        return remove(size - 1);
    }
    /**
     * 删除
     * @param index
     * @return
     */
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("delete failed, index is "+ index);
        }
        E val = data[index];
        for(int i = index; i < size; i ++) {
            data[i] = data[i + 1];
        }
        data[size] = null;
        size --;
        return val;
    }
    public void removeElement(E e) {
        int index = getIndex(e);
        if (index >= 0) {
            remove(index);
        }
    }
    //改
    //查
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("get failed, index is "+ index);
        }
        return data[index];
    }
    public E getFirst() {
        return get(0);
    }

    public E getLast() {
        return get(size - 1);
    }
    public boolean contains(E e) {
        for(E k : data) {
            if (k.equals(e)) {
                return true;
            }

        }
        return false;
    }

    public int getIndex(E e) {
        for(int i = 0; i < size; i ++) {
            if (data[i].equals(e)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public String toString() {
        return Arrays.toString(Arrays.copyOf(data, size));
    }

    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        System.out.println(i << 1);
    }
}
